#include <ESP8266WiFi.h>
//#include <WiFi.h>//ESP32使用这一句
#include <WiFiClientSecure.h> 

//数据初始化部分
const char* host = "192.168.30.24"; //需要访问的域名
const int httpsPort = 8999;  // 需要访问的端口
const String url = "/input";   // 需要访问的地址
int DSPIN = D4; // 使用D4引脚来接收数据

void SmartConfig()
{
  WiFi.mode(WIFI_STA);
  Serial.println("\r\nWait for Smartconfig...");
  WiFi.beginSmartConfig();
  while (1)
  {
    Serial.print(".");
    delay(500);                   // wait for a second
    if (WiFi.smartConfigDone())
    {
      Serial.println("SmartConfig Success");
      Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
      Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
      break;
    }
  }
}

bool AutoConfig()
{
    WiFi.begin();
    //20秒连接不上自动进入配置程序
    for (int i = 0; i < 20; i++)
    {
        int wstatus = WiFi.status();
        if (wstatus == WL_CONNECTED)
        {
          Serial.println("WIFI SmartConfig Success");
          Serial.printf("SSID:%s", WiFi.SSID().c_str());
          Serial.printf(", PSW:%s\r\n", WiFi.psk().c_str());
          Serial.print("LocalIP:");
          Serial.print(WiFi.localIP());
          Serial.print(" ,GateIP:");
          Serial.println(WiFi.gatewayIP());
          return true;
        }
        else
        {
          Serial.print("WIFI AutoConfig Waiting......");
          Serial.println(i);
          delay(1000);
        }
    }
    Serial.println("WIFI AutoConfig Faild!" );
    return false;
}

void setup() {
  Serial.begin(115200);
  delay(100);
  if (!AutoConfig())
  {
    SmartConfig();
  }
  pinMode(0, INPUT);//定义gpio0脚为输入模式，也就是和flash键连接的脚
  pinMode(16, OUTPUT);//定义gpio16脚为输出模式，也就是板载蓝灯
  digitalWrite(0, HIGH);//定义gpio0脚为高电平，注意，不能长期低电平，低电平就进入刷机模式
  digitalWrite(16, HIGH);//定义gpio0脚为高电平，高电平led不亮，因为led两端都是高电平
}

void loop()
{
    if(GPIO_INPUT_GET(0) == LOW)//按下flash键，gpio0变为低电平，如果gpio0脚为低电平，则进入wifi重置模式
    {
          delay(500);
        Serial.print("Rest wifi...\n");
        digitalWrite(16, LOW);//亮板载蓝灯
          delay(1000);
          Serial.print("wifi Resting...\n");
        SmartConfig();  
    }

    //    温度数据接收部分
    Serial.print("connecting to ");  
    Serial.println(host);  
  
    WiFiClient client;  
  
    /**
     * 测试是否正常连接
     */
    if (!client.connect(host, httpsPort)) {  
      Serial.println("connection failed");  
      return;  
    }  
    
    // put your main code here, to run repeatedly:
    double temp = TempRead();
    temp *= 0.0625;//转换精度为0.0625/LSB
    Serial.println(temp);
    delay(1000);
  
    
    String postRequest =(String)("GET ") + url+"?sn=esp8266_01&key=temp&value="+ temp  + "/ HTTP/1.1\r\n" +  
      "Content-Type: text/html;charset=utf-8\r\n" +  
      "Host: " + host + "\r\n" + 
      "User-Agent: BuildFailureDetectorESP8266\r\n" +
      "Connection: Keep Alive\r\n\r\n";  
    Serial.println(postRequest);  
    client.print(postRequest);  // 发送HTTP请求
  
    /**
     * 展示返回的所有信息
     */
    String line = client.readStringUntil('\n');
    while(line.length() != 0){
      Serial.println(line);
      line = client.readStringUntil('\n');
    }
    Serial.println(line);
    client.stop();
    delay(1000); 

}

boolean DS18B20_Init()
{
  pinMode(DSPIN, OUTPUT);
  digitalWrite(DSPIN, HIGH);
  delayMicroseconds(5);
  digitalWrite(DSPIN, LOW);
  delayMicroseconds(750);//480-960
  digitalWrite(DSPIN, HIGH);
  pinMode(DSPIN, INPUT);
  int t = 0;
  while(digitalRead(DSPIN))
  {
    t++;
    if(t > 60) return false;
    delayMicroseconds(1);
  }
  t = 480 - t;
  pinMode(DSPIN, OUTPUT);
  delayMicroseconds(t);
  digitalWrite(DSPIN, HIGH);
  return true;
}
 
void DS18B20_Write(byte data)
{
  pinMode(DSPIN, OUTPUT);
  for(int i=0; i<8; i++)
  {
    digitalWrite(DSPIN, LOW);
    delayMicroseconds(10);
    if(data & 1) digitalWrite(DSPIN, HIGH);
    else digitalWrite(DSPIN, LOW);
    data >>= 1;
    delayMicroseconds(50);
    digitalWrite(DSPIN, HIGH);
  }
}
 
byte DS18B20_Read()
{
  pinMode(DSPIN, OUTPUT);
  digitalWrite(DSPIN, HIGH);
  delayMicroseconds(2);
  byte data = 0;
  for(int i=0; i<8; i++)
  {
    digitalWrite(DSPIN, LOW);
    delayMicroseconds(1);
    digitalWrite(DSPIN, HIGH);
    pinMode(DSPIN, INPUT);
    delayMicroseconds(5);
    data >>= 1;
    if(digitalRead(DSPIN)) data |= 0x80;
    delayMicroseconds(55);
    pinMode(DSPIN, OUTPUT);
    digitalWrite(DSPIN, HIGH);
  }
  return data;
}
 
int TempRead()
{
  if(!DS18B20_Init()) return 0;
  DS18B20_Write(0xCC);//发跳过ROM命令
  DS18B20_Write(0x44);//发读开始转换命令
  if(!DS18B20_Init()) return 0;
  DS18B20_Write(0xCC);//发跳过ROM命令
  DS18B20_Write(0xBE);//读寄存器，共九字节，前两字节为转换值
  int temp = DS18B20_Read();//低字节
  temp |= DS18B20_Read() << 8;//高字节
  return temp;
}
